package com.jy.appmarket.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jy.app.market.idata.card.Card;
import com.jy.app.market.idata.card.CardApkRecommend;
import com.jy.app.market.idata.data.Apk;
import com.jy.app.market.idata.data.Apk.ScreenShots;
import com.jy.app.market.idata.data.CommentList;
import com.jy.app.market.idata.data.PageCard;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.cards.ApkRecommendUICard;
import com.jy.appmarket.cards.ApkUICard;
import com.jy.appmarket.cards.AppDetailCommentUICard;
import com.jy.appmarket.cards.AppDetailInfoUICard;
import com.jy.appmarket.cards.AppDetailIntroUICard;
import com.jy.appmarket.cards.AppDetailTagsUICard;
import com.jy.appmarket.cards.DownloadableUICard;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.newnetwork.RequestQueue;
import com.jy.appmarket.newnetwork.Response.ErrorListener;
import com.jy.appmarket.newnetwork.Response.Listener;
import com.jy.appmarket.newnetwork.VolleyError;
import com.jy.appmarket.newnetwork.api.ApiRequest;
import com.jy.appmarket.newnetwork.api.ApiRequest.ParamBuilder;
import com.jy.appmarket.newnetwork.api.ApiResult;
import com.jy.appmarket.newnetwork.api.MarketApi;
import com.jy.appmarket.receiver.PushReceiver;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.statistics.SourceConstants;
import com.jy.appmarket.utils.ActivateStatistics;
import com.jy.appmarket.utils.IdataUtils;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.NotificationUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.jy.appmarket.view.LoadingView;
import com.jy.appmarket.view.ProgressTextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.umeng.analytics.MobclickAgent;

import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import it.gmariotti.cardslib.library.view.CardView;

public class AppDetailActivity extends DownloadActivity
		implements View.OnClickListener, Listener<ApiResult>, ErrorListener {
	private static final String TAG = AppDetailActivity.class.getSimpleName();
	public static final String EXTRA_NAME = "app_detail_name";
	public static final String EXTRA_PKG = "app_detail_package";
	public static final String EXTRA_SOURCE = "app_source";
	public static final String PUSH_ID = "push_id";

	private String mName;
	private String mPackage;
	private String mSource;
	private ScrollView mScrollView;
	private LoadingView mLoadingView;
	private View mDownloadView;

	private Apk mApk;
	private CardApkRecommend mRecommend;
	private CommentList mComment;
	private String mDlId;
	private DownloadItem mDownloadItem;

	private ProgressTextView mStatus;
	private ProgressBar mProgress;
	private Drawable mStyleBlue;
	private Drawable mStyleOrange;
	private DecimalFormat sProgressFormat = new DecimalFormat("##0.00");
	private float mScreenShotImageHeight;
	private String mIconUrl;

	private int[] mScreenShotSize = null;

	private ApiRequest detailReq;
	private ApiRequest recommendReq;
	private ApiRequest commentReq;

	private RequestQueue mQueue;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_appdetail);
		getExtras();
		initTitle();
		initViews();
		mQueue = MarketApi.newApiRequestQueue(this);
		loadData();
		ActivateStatistics.ActivateFrom(this, this.getClass().getSimpleName());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		if (mApk != null && mApk.getPermissions() != null) {
			// Log.e(TAG, "vc in detail:" + mApk.getVersionCode());
			getMenuInflater().inflate(R.menu.app_detail, menu);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.action_permission:
			Intent it = new Intent(this, PermissionListActivity.class);
			it.putExtra(PermissionListActivity.EXTRA_PERMISSIONS, mApk.getPermissions());
			startActivity(it);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		goBack();
		mQueue.stop();
		ImageLoader.getInstance().stop();
	}

	private void loadData() {
		mScrollView.setVisibility(View.GONE);
		findViewById(R.id.appdetail_download_divider).setVisibility(View.GONE);
		mDownloadView.setVisibility(View.GONE);
		mLoadingView.setVisibility(View.VISIBLE);
		mLoadingView.showWaitView(R.string.ptr1_loading_wait);

		Map<String, String> params = ParamBuilder.create().add("packageName", mPackage).build();
		detailReq = ApiRequest.get("app", params, this, this);
		recommendReq = ApiRequest.get("recommend_v2", params, this, this);

		ParamBuilder p2 = ParamBuilder.create().add("pageNo", 0).add("packageName", mPackage).add("versionCode", 1);

		commentReq = ApiRequest.get("get_comment", p2.build(), this, this);

		mQueue.add(commentReq);
		mQueue.add(recommendReq);
		mQueue.add(detailReq);
	}

	private void getExtras() {
		if (getIntent() == null) {
			return;
		}
		Bundle extras = getIntent().getExtras();
		if (extras == null) {
			return;
		}
		mName = extras.getString(EXTRA_NAME);
		mPackage = extras.getString(EXTRA_PKG);
		mSource = extras.getString(EXTRA_SOURCE);
		if (TextUtils.isEmpty(mSource)) {
			LogUtil.w(TAG, mName + " source is empty");
		}

		if (SourceConstants.PUSH_APP.equalsIgnoreCase(mSource)) {
			NotificationUtil.cancelNotification(this, PushReceiver.NOTIFICATION_APP_ID);
		}
		String pushId = extras.getString(PUSH_ID);
		if (!TextUtils.isEmpty(pushId)) {
			PushReceiver.sendConsumeBroadcast(this, pushId, 1);
		}
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(R.string.detail);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	private void initViews() {
		DisplayMetrics dm = getResources().getDisplayMetrics();
		mScreenShotImageHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,
				getResources().getDimension(R.dimen.appdetail_screenshot_image_height), dm);

		mLoadingView = findViewById(R.id.loading_view_layout);
		mScrollView = findViewById(R.id.appdetail_scrollview);
		mDownloadView = findViewById(R.id.appdetail_download_view);
		mProgress = findViewById(R.id.appdetail_progressbar);
		mStatus = findViewById(R.id.appdetail_progresstextview);
		mStatus.setOnClickListener(this);

		mStyleBlue = getResources().getDrawable(R.drawable.download_progress_download);
		mStyleOrange = getResources().getDrawable(R.drawable.download_progress_other);

		mLoadingView.setVisibility(View.VISIBLE);
		mLoadingView.setOnClickListener(new LoadingView.OnClickListener() {
			@Override
			public void onLoadingViewClick(View view) {
				loadData();
			}
		});
		mScrollView.setVisibility(View.GONE);
		findViewById(R.id.appdetail_download_divider).setVisibility(View.GONE);
		mDownloadView.setVisibility(View.GONE);
	}

	private void showContent() {
		mLoadingView.setVisibility(View.GONE);

		mDlId = DownloadUtils.generateDownloadId(mApk.getPackageName(), mApk.getVersionCode());
		mIconUrl = IdataUtils.getIconUrl(mApk.getIcons());
		mDownloadItem = getDownloadById(mDlId);

		CardView detailCardView = findViewById(R.id.appdetail_info_card);
		AppDetailInfoUICard detailCard = new AppDetailInfoUICard(this, mApk);
		detailCardView.setCard(detailCard);

		RecyclerView rv = findViewById(R.id.appdetail_screenshots_recyclerview);
		if (mApk.getScreenshots() == null || mApk.getScreenshots().getSmall() == null) {
			rv.setVisibility(View.GONE);
		} else {
			rv.setVisibility(View.VISIBLE);
			rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
			rv.setHasFixedSize(true);
			rv.setAdapter(new ScreenShotAdapter(mApk.getScreenshots().getSmall()));

			if (mApk.getScreenshots().getSmall().size() != 0 && mScreenShotSize == null) {
				mScreenShotSize = new int[mApk.getScreenshots().getSmall().size() * 2];
			}
		}

		CardView introCardView = findViewById(R.id.appdetail_intro_card);
		AppDetailIntroUICard introCard = new AppDetailIntroUICard(this, mApk);
		introCardView.setCard(introCard);
		// comment
		CardView commentCardView = findViewById(R.id.appdetail_comment_card);

		AppDetailCommentUICard comCard = new AppDetailCommentUICard(this, mComment, mApk);
		commentCardView.setCard(comCard);

		CardView tagsCardView = findViewById(R.id.appdetail_app_tags_card);
		if (mApk.getTags() == null || mApk.getTags().length == 0) {
			tagsCardView.setVisibility(View.GONE);
		} else {
			List<String> tags = new ArrayList<String>();
			for (String s : mApk.getTags()) {
				if (s != null && s.length() >= 2 && s.length() <= 4) {
					tags.add(s);
				}
			}
			if (tags == null || tags.isEmpty()) {
				tagsCardView.setVisibility(View.GONE);
			} else {
				AppDetailTagsUICard tagsCard = new AppDetailTagsUICard(this, tags);
				tagsCardView.setVisibility(View.VISIBLE);
				tagsCardView.setCard(tagsCard);
			}
		}

		CardView apkRecommendCardView = findViewById(R.id.appdetail_apk_recommend_card);

		if (mRecommend == null) {
			apkRecommendCardView.setVisibility(View.GONE);
		} else {
			apkRecommendCardView.setVisibility(View.VISIBLE);
			ApkRecommendUICard recommendCard = new ApkRecommendUICard(this, mRecommend);
			recommendCard.setApkSource(new ApkSource("recommend", mPackage, null, null, null, null, null));
			addFileListener(recommendCard);
			apkRecommendCardView.setCard(recommendCard);
		}

		TextView appSource = findViewById(R.id.appdetail_app_source);
		appSource.setText("技术支持：豌豆荚");

		setupDownload();
		mLoadingView.setVisibility(View.GONE);
		mScrollView.setVisibility(View.VISIBLE);
		findViewById(R.id.appdetail_download_divider).setVisibility(View.VISIBLE);
		mDownloadView.setVisibility(View.VISIBLE);
		invalidateOptionsMenu();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.appdetail_progresstextview:
			Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();
			break;
		}
	}

	@Override
	public void onPackageInstalled(String pkgName) {
		if (mApk == null) {
			return;
		}
		if (pkgName.equals(mApk.getPackageName())) {
			setupDownload();
		}
	}

	@Override
	public void onPackageUninstalled(String pkgName) {
		if (mApk == null) {
			return;
		}
		if (pkgName.equals(mApk.getPackageName())) {
			setupDownload();
		}
	}

	@Override
	public void onProgressChanged(String id, long downloadedBytes, long speed) {
		super.onProgressChanged(id, downloadedBytes, speed);
		if (mDlId != null && mDlId.equals(id)) {
			if (mDownloadItem != null) {
				mDownloadItem.setDownloadedSize(downloadedBytes);
				setupDownload();
			}
		}
	}

	@Override
	public void onDownloadCreated(DownloadItem di) {
		super.onDownloadCreated(di);
		if (!di.getId().equals(mDlId)) {
			return;
		}
		mDownloadItem = di;
		setupDownload();
	}

	@Override
	public void onDownloadChanged(DownloadItem di) {
		super.onDownloadChanged(di);
		if (!di.getId().equals(mDlId)) {
			return;
		}
		mDownloadItem = di;
		setupDownload();
	}

	@Override
	public void onDownloadRemoved(String id) {
		super.onDownloadRemoved(id);
		if (!id.equals(mDlId)) {
			return;
		}
		mDownloadItem = null;
		setupDownload();
	}

	private void setupDownload() {
		int status = getDownloadStatus(mDlId, mApk.getPackageName(), mApk.getVersionCode());

		switch (status) {
		case DownloadService.STATUS_INSTALLED: {
			mProgress.setProgressDrawable(mStyleOrange);
			mProgress.setProgress(0);
			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mStatus.setProgress(0);
			mStatus.setText(R.string.open);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent it = getPackageManager().getLaunchIntentForPackage(mApk.getPackageName());
					try {
						startActivity(it);
					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(AppDetailActivity.this, "打开失败", Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
			break;
		case DownloadService.STATUS_CAN_INSTALL: {
			mProgress.setProgressDrawable(mStyleBlue);
			mProgress.setProgress(mProgress.getMax());

			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mStatus.setProgress(0);
			mStatus.setText(R.string.install);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					installApk(mDownloadItem);
				}
			});
		}
			break;
		case DownloadService.STATUS_NO_STATUS: {
			mProgress.setProgressDrawable(mStyleBlue);
			mProgress.setProgress(mProgress.getMax());

			String sizeStr = Formatter.formatFileSize(this, ApkUICard.safeInt(mApk.getBytes()));
			mStatus.setText(getString(R.string.download) + "  " + sizeStr);
			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mStatus.setProgress(0);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					addDownload(mApk.getDownloadUrl().getUrl(), mApk.getTitle(), mApk.getPackageName(),
							mApk.getVersionName(), mApk.getVersionCode(), mApk.getMd5(), mIconUrl, mSource);
					if (DownloadUtils.isMobileNetwork(AppDetailActivity.this)) {
						Toast.makeText(AppDetailActivity.this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}

				}
			});
		}
			break;
		case DownloadService.STATUS_DOWNLOADING: {
			float per = getProgress(mDownloadItem, mApk, mDlId);
			mProgress.setProgressDrawable(mStyleBlue);
			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mProgress.setProgress((int) (per * 100));
			mStatus.setText(getString(R.string.downloading) + "  " + sProgressFormat.format(per) + "%");
			mStatus.setProgress(per / 100);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					stopDownload(mDlId);
				}
			});
		}
			break;
		case DownloadService.STATUS_PAUSED_BY_USER: {
			float per = getProgress(mDownloadItem, mApk, mDlId);
			mProgress.setProgressDrawable(mStyleBlue);
			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mProgress.setProgress((int) (per * 100));
			mStatus.setProgress(per / 100);
			mStatus.setText(R.string.go_on);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// Log.e(TAG, "vc:" + mApk.getVersionCode() + " url:"
					// + mApk.getDownloadUrl().getUrl());

					startDownload(mDlId);
					if (DownloadUtils.isMobileNetwork(AppDetailActivity.this)) {
						Toast.makeText(AppDetailActivity.this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
				}
			});
		}
			break;
		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK: {
			float per = getProgress(mDownloadItem, mApk, mDlId);
			mProgress.setProgressDrawable(mStyleBlue);
			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mProgress.setProgress((int) (per * 100));
			mStatus.setProgress(per / 100);
			mStatus.setText(R.string.go_on);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					startDownload(mDlId);
					if (DownloadUtils.isMobileNetwork(AppDetailActivity.this)) {
						Toast.makeText(AppDetailActivity.this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
				}
			});
		}
			break;
		case DownloadService.STATUS_PAUSED_BY_ERROR: {
			float per = getProgress(mDownloadItem, mApk, mDlId);
			mProgress.setProgressDrawable(mStyleOrange);
			mProgress.setProgress((int) (per * 100));

			mStatus.setProgressTextColorRes(R.color.download_btn_orange_style_text);
			mStatus.setText(R.string.retry);
			mStatus.setProgress(per / 100);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					startDownload(mDlId);
					if (DownloadUtils.isMobileNetwork(AppDetailActivity.this)) {
						Toast.makeText(AppDetailActivity.this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
				}
			});
		}
			break;
		case DownloadService.STATUS_PREPARE_TO_DOWNLOAD: {
			float per = getProgress(mDownloadItem, mApk, mDlId);
			mProgress.setProgressDrawable(mStyleBlue);
			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mProgress.setProgress((int) (per * 100));
			mStatus.setText(getString(R.string.downloading) + "  " + sProgressFormat.format(per) + "%");
			mStatus.setProgress(per / 100);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {

				}
			});
		}

			break;
		case DownloadService.STATUS_PREPARE_TO_STOP: {
			float per = getProgress(mDownloadItem, mApk, mDlId);
			mProgress.setProgressDrawable(mStyleBlue);
			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mProgress.setProgress((int) (per * 100));
			mStatus.setProgress(per / 100);
			mStatus.setText(R.string.go_on);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
				}
			});
		}
			break;
		case DownloadService.STATUS_PENDING:
			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mStatus.setProgress(0);
			mStatus.setText(R.string.waiting);

			mProgress.setProgressDrawable(mStyleBlue);
			mProgress.setProgress(0);

			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					stopDownload(mDlId);
				}
			});
			break;
		case DownloadService.STATUS_INSTALLING: {
			mProgress.setProgressDrawable(mStyleBlue);
			mProgress.setProgress(mProgress.getMax());

			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mStatus.setProgress(0);
			mStatus.setText(R.string.installing);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					installApk(mDownloadItem);
				}
			});
		}
			break;
		case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE: // 下载过期状态，强制处理为有更新状态，点击后重新开始下载
			mProgress.setProgressDrawable(mStyleBlue);
			mProgress.setProgress(mProgress.getMax());

			if (PackageUtils.isPackageInstalled(this, mApk.getPackageName())) {
				mStatus.setText(getString(R.string.update) + "  " + Formatter.formatFileSize(this, mApk.getBytes()));
			} else {
				mStatus.setText(getString(R.string.download) + "  " + Formatter.formatFileSize(this, mApk.getBytes()));
			}

			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mStatus.setProgress(0);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					removeOutofDateDownloads(mApk.getPackageName());
					addDownload(mApk.getDownloadUrl().getUrl(), mApk.getTitle(), mApk.getPackageName(),
							mApk.getVersionName(), mApk.getVersionCode(), mApk.getMd5(), mIconUrl, mSource);
					if (DownloadUtils.isMobileNetwork(AppDetailActivity.this)) {
						Toast.makeText(AppDetailActivity.this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}

				}
			});
			break;
		case DownloadService.STATUS_NEED_TO_UPDATE:
			mProgress.setProgressDrawable(mStyleBlue);
			mProgress.setProgress(mProgress.getMax());

			mStatus.setText(getString(R.string.update) + "  " + Formatter.formatFileSize(this, mApk.getBytes()));
			mStatus.setProgressTextColorRes(R.color.download_btn_blue_style_text);
			mStatus.setProgress(0);
			mStatus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					addDownload(mApk.getDownloadUrl().getUrl(), mApk.getTitle(), mApk.getPackageName(),
							mApk.getVersionName(), mApk.getVersionCode(), mApk.getMd5(), mIconUrl, mSource);
					if (DownloadUtils.isMobileNetwork(AppDetailActivity.this)) {
						Toast.makeText(AppDetailActivity.this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}

				}
			});
			break;
		default:
			LogUtil.w(TAG, "unknown status:" + status);
			break;
		}
	}

	private float getProgress(DownloadItem di, Apk apk, String dlId) {
		if (di != null) {
			return getProgress(di.getTotalSize(), di.getDownloadedSize());
		} else {
			long totalSize = DownloadableUICard.safeInt(apk.getBytes());
			long downloadedSize = getDownloadedFileSizeById(dlId);
			return getProgress(totalSize, downloadedSize);
		}
	}

	private float getProgress(long totalSize, long downloadedSize) {

		long total = totalSize;
		if (total == 0) {
			total = Long.MAX_VALUE;
		}

		float per = downloadedSize * 100.0f / total;

		if (per > 100) {
			per = 100;
		} else if (per < 0) {
			per = 0;
		}
		return per;
	}

	private static class ViewHolder extends RecyclerView.ViewHolder {
		public ImageView imageView;

		public ViewHolder(View view) {
			super(view);
			imageView = view.findViewById(R.id.appdetail_gallery_item_image);
		}

		@Override
		public String toString() {
			return super.toString() + " '" + imageView;
		}
	}

	private int getStatusBarHeight() {
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}

	private void goBack() {
		AppMarketApplication app = (AppMarketApplication) getApplication();
		if (app.isAppRunning()) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setClass(this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			startActivity(intent);
		} else {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		}
		finish();
	}

	@Override
	public void onResponse(ApiResult response) {
		if (!response.isOK()) {
			onErrorResponse(new VolleyError("status error"));
			return;
		}
		int seq = response.getSequence();

		if (detailReq != null && detailReq.getSequence() == seq) {
			Apk apk = response.getData(Apk.class);
			if (apk == null) {
				mLoadingView.showErrorView(getString(R.string.ptrl_refresh_fail));
				return;
			}
			mApk = apk;
			showContent();
		} else if (recommendReq != null && recommendReq.getSequence() == seq) {
			PageCard card = response.getData(PageCard.class);
			if (card == null) {
				return;
			}
			List<Card> cardList = card.getCards();
			if (cardList == null || cardList.isEmpty()) {
				return;
			}
			Card first = cardList.get(0);
			if (first != null && (first instanceof CardApkRecommend)) {
				mRecommend = (CardApkRecommend) first;
			}
		} else if (commentReq != null && commentReq.getSequence() == seq) {
			mComment = response.getData(CommentList.class);
		}
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		ApiRequest.cancel(detailReq);
		ApiRequest.cancel(commentReq);
		ApiRequest.cancel(recommendReq);

		Toast.makeText(this, R.string.network_error, Toast.LENGTH_SHORT).show();
		mLoadingView.setVisibility(View.VISIBLE);
		mLoadingView.showErrorView(getString(R.string.ptrl_refresh_fail));
		mScrollView.setVisibility(View.GONE);
		findViewById(R.id.appdetail_download_divider).setVisibility(View.VISIBLE);
		mDownloadView.setVisibility(View.GONE);
	}

	private class ScreenShotAdapter extends RecyclerView.Adapter<ViewHolder> {
		private List<String> mUrls;

		public ScreenShotAdapter(List<String> urls) {
			mUrls = urls;
		}

		@Override
		public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.appdetail_gallery_item, parent,
					false);
			ViewHolder h = new ViewHolder(view);
			return h;
		}

		@Override
		public void onBindViewHolder(final ViewHolder holder, final int position) {
			ImageLoader.getInstance().displayImage(mUrls.get(position), holder.imageView,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
							if (loadedImage == null || loadedImage.getHeight() == 0) {
								return;
							}
							float width = 1.0f * loadedImage.getWidth() * mScreenShotImageHeight
									/ loadedImage.getHeight();
							ViewGroup.LayoutParams lp = view.getLayoutParams();
							lp.width = (int) width;
							view.setLayoutParams(lp);
							view.setVisibility(View.VISIBLE);

							if (mScreenShotSize != null && (position * 2 + 1) < mScreenShotSize.length) {
								mScreenShotSize[position * 2] = loadedImage.getWidth();
								mScreenShotSize[position * 2 + 1] = loadedImage.getHeight();
							}
						}
					});
			holder.imageView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					ScreenShots ss = mApk.getScreenshots();
					if (ss != null && ss.getSmall() != null && ss.getNormal() != null) {

						ArrayList<String> small = new ArrayList<String>();
						for (String s : ss.getSmall()) {
							small.add(s);
						}
						ArrayList<String> normal = new ArrayList<String>();
						for (String s : ss.getNormal()) {
							normal.add(s);
						}

						// 计算view的位置
						int[] p = new int[2];
						v.getLocationInWindow(p);
						Rect rect = new Rect();
						rect.left = p[0];
						rect.top = p[1] - getStatusBarHeight();
						rect.right = rect.left + v.getWidth();
						rect.bottom = rect.top + v.getHeight();

						Intent intent = new Intent(v.getContext(), ScreenShotsActivity.class);
						intent.setSourceBounds(rect);
						intent.putStringArrayListExtra(ScreenShotsActivity.EXTRA_SMALL_LIST, small);
						intent.putStringArrayListExtra(ScreenShotsActivity.EXTRA_NORMAL_LIST, normal);

						if (mScreenShotSize != null) {
							intent.putExtra(ScreenShotsActivity.EXTRA_SMALL_IMAGE_SIZE_LIST, mScreenShotSize);
						}
						intent.putExtra(ScreenShotsActivity.EXTRA_INDEX, position);
						ImageView image = (ImageView) v;
						ScreenShotsActivity.DrawableHolder.index = position;

						// ScreenShotsActivity.DrawableHolder.drawable =
						// image.getDrawable();
						ScreenShotsActivity.DrawableHolder.drawable = image.getDrawable().getConstantState()
								.newDrawable(); // 传入一个新的drawable，避免在screenshot
												// activity中修改drawable后对详情中drawable影响
						v.getContext().startActivity(intent);
					} else {
						Toast.makeText(v.getContext(), "无法查看大图", Toast.LENGTH_SHORT).show();
					}
				}
			});
		}

		@Override
		public int getItemCount() {
			return mUrls.size();
		}
	}
}
